<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>药店管理系统</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="/layui/css/layui.css" rel="stylesheet">
    <script src="/jquery/jquery-3.6.0.js"></script>
</head>

<body>
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo layui-hide-xs layui-bg-black">小药店管理系统</div>
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item layui-hide layui-show-sm-inline-block">
                <a>
                    <img src="//unpkg.com/outeres@0.0.10/img/layui/icon-v2.png" class="layui-nav-img">
                    欢迎, <span>admin</span>
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="javascript:;" onclick="logout()">退出</a></dd>
                </dl>
            </li>
        </ul>
    </div>
    <div class="layui-side layui-bg-black">
        <div class="layui-side-scroll">
            <ul class="layui-nav layui-nav-tree" lay-filter="test">
                <li class="layui-nav-item layui-nav-itemed">
                    <a class="" href="javascript:;">采购管理</a>
                    <dl class="layui-nav-child">
                        <dd><a href="../supplier/supplier.html">供应商信息管理</a></dd>
                        <dd><a href="../supplier/drug.html">药品信息管理</a></dd>
                        <dd><a href="../procurement/add.html">采购单添加</a></dd>
                        <dd><a href="../procurement/list.html">采购单管理</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">销售管理</a>
                    <dl class="layui-nav-child">
                        <dd><a href="add_xiaoshoudan.html">销售单添加</a></dd>
                        <dd><a href="xiaoshoumingxi.html">销售单管理</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">药店统计管理</a>
                    <dl class="layui-nav-child">
                        <dd><a href="../statistics/instock.html">入库统计</a></dd>
                        <dd><a href="../statistics/sales.html">销售统计</a></dd>
                        <dd><a href="../statistics/stock.html">库存查询</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">人事管理</a>
                    <dl class="layui-nav-child">
                        <dd><a href="../yuangong/add_yuangong.html">员工添加</a></dd>
                        <dd><a href="../yuangong/yuangong.html">员工管理</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">打印管理</a>
                    <dl class="layui-nav-child">
                        <dd><a href="../print/ruku.html">入库单</a></dd>
                        <dd><a href="../print/chuku.html">出库单</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">系统管理</a>
                    <dl class="layui-nav-child">
                        <dd><a href="../user/xiuGaiMiMa.html">修改密码</a></dd>
                    </dl>
                </li>
            </ul>
        </div>
    </div>
    <div class="layui-body">
        <div class="container">
            <div class="layui-row">
                <div class="layui-col-md12">
                    <div class="layui-breadcrumb" style="margin: 15px 0;">
                        <a href="../index.html">首页</a>
                        <a href="xiaoshoumingxi.html">销售明细</a>
                        <a href="add_xiaoshoudan.html">添加销售单</a>
                    </div>
                </div>
            </div>
            <div class="layui-card" style="margin: 15px;">
                <div class="layui-card-header" style="font-size: 18px; font-weight: bold;">
                    <i class="layui-icon layui-icon-form"></i> 添加销售单
                </div>
                <div class="layui-card-body">
                    <form class="layui-form" id="xiaoshouForm" lay-filter="xiaoshouForm">
                        <div class="layui-form-item">
                            <label class="layui-form-label">销售单号</label>
                            <div class="layui-input-block">
                                <input type="text" name="danjuhao" required lay-verify="required" class="layui-input" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">销售时间</label>
                            <div class="layui-input-block">
                                <input type="text" name="shijian" required lay-verify="required" class="layui-input" id="shijian" readonly>
                            </div>
                        </div>
                        
                        <!-- 药品选择和数量输入 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">选择药品</label>
                            <div class="layui-input-inline" style="width: 200px;">
                                <select name="drugId" lay-filter="drugSelect">
                                    <option value="">请选择药品</option>
                                </select>
                            </div>
                            <div class="layui-input-inline" style="width: 150px;">
                                <input type="number" name="quantity" placeholder="请输入数量" class="layui-input" min="1">
                            </div>
                            <div class="layui-input-inline" style="width: 150px;">
                                <input type="text" name="price" placeholder="单价" class="layui-input" readonly>
                            </div>
                            <button type="button" class="layui-btn" lay-submit lay-filter="addDetail">添加到明细</button>
                        </div>

                        <!-- 明细表格 -->
                        <table id="detailTable" lay-filter="detailTable"></table>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">总金额</label>
                            <div class="layui-input-block">
                                <input type="text" name="zongjia" class="layui-input" readonly>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">负责人</label>
                            <div class="layui-input-block">
                                <select name="responsiblePerson" lay-verify="required">
                                    <option value="">请选择负责人</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">备注</label>
                            <div class="layui-input-block">
                                <textarea name="beizhu" placeholder="请输入备注（选填）" class="layui-textarea"></textarea>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="submitForm">提交</button>
                                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="/layui/layui.js"></script>
<script>
    // 退出功能
    function logout() {
        layui.use(['jquery', 'layer'], function(){
            var $ = layui.$;
            var layer = layui.layer;
            
            $.ajax({
                url: '/user/logout',
                type: 'GET',
                success: function(res) {
                    if(res.code === 0) {
                        window.location.href = '/login/login.html';
                    } else {
                        layer.msg(res.msg || '退出失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('服务器错误', {icon: 2});
                }
            });
        });
    }

    layui.use(['element', 'form', 'laydate', 'table'], function(){
        var element = layui.element;
        var form = layui.form;
        var laydate = layui.laydate;
        var table = layui.table;
        var $ = layui.$;
        
        $('.layui-nav-item').removeClass('layui-nav-itemed');
        $('dd').removeClass('layui-this');
        var $salesNav = $('a:contains("销售管理")').parent();
        $salesNav.addClass('layui-nav-itemed');
        $('a:contains("销售单添加")').parent().addClass('layui-this');
        
        // 生成销售单号
        function generateOrderNo() {
            var now = new Date();
            var year = now.getFullYear();
            var month = String(now.getMonth() + 1).padStart(2, '0');
            var day = String(now.getDate()).padStart(2, '0');
            var hour = String(now.getHours()).padStart(2, '0');
            var minute = String(now.getMinutes()).padStart(2, '0');
            var second = String(now.getSeconds()).padStart(2, '0');
            var random = String(Math.floor(Math.random() * 1000)).padStart(3, '0');
            return 'XS' + year + month + day + hour + minute + second + random;
        }
        
        // 初始化日期选择器
        laydate.render({
            elem: '#shijian',
            type: 'datetime',
            value: new Date()
        });
        
        // 设置销售单号
        $('input[name="danjuhao"]').val(generateOrderNo());
        
        // 加载负责人列表
        $.get('/api/procurement/employees', function(res){
            if(res.code === 0){
                var html = '<option value="">请选择负责人</option>';
                res.data.forEach(function(item){
                    html += '<option value="' + item.name + '">' + item.name + '</option>';
                });
                $('select[name="responsiblePerson"]').html(html);
                form.render('select');
            }
        });
        
        // 初始化明细表格
        var detailTable = table.render({
            elem: '#detailTable',
            cols: [[
                {field: 'drugName', title: '药品名称', width: 200},
                {field: 'quantity', title: '数量', width: 100},
                {field: 'price', title: '单价', width: 100},
                {field: 'amount', title: '金额', width: 100},
                {title: '操作', width: 100, templet: '#operationTpl', fixed: 'right'}
            ]],
            data: [],
            limit: 1000
        });
        
        // 监听药品选择
        form.on('select(drugSelect)', function(data){
            if(data.value){
                // 获取药品信息
                $.get('/api/drug/' + data.value, function(res){
                    if(res.code === 0){
                        var drug = res.data;
                        $('input[name="price"]').val(drug.price);
                        // 保存库存数量到input的data属性
                        $('input[name="quantity"]').data('stock', drug.stock || 0);
                    } else {
                        layer.msg('获取药品信息失败');
                    }
                });
            } else {
                $('input[name="price"]').val('');
                $('input[name="quantity"]').data('stock', 0);
            }
        });
        
        // 监听数量输入
        $('input[name="quantity"]').on('input', function(){
            var quantity = parseInt($(this).val());
            var stock = $(this).data('stock') || 0;
            
            if(quantity > stock){
                layer.msg('当前库存不足，仅剩 ' + stock + ' ' + $('select[name="drugId"] option:selected').data('unit'), {
                    icon: 2,
                    time: 2000
                });
            }
        });
        
        // 加载药品列表
        $.get('/api/drug/list', function(res){
            if(res.code === 0){
                var html = '<option value="">请选择药品</option>';
                res.data.forEach(function(item){
                    html += '<option value="' + item.id + '" data-unit="' + (item.unit || '盒') + '">' + item.drugName + '</option>';
                });
                $('select[name="drugId"]').html(html);
                form.render('select');
            }
        });
        
        // 添加明细
        form.on('submit(addDetail)', function(data){
            if(!data.field.drugId){
                layer.msg('请选择药品');
                return false;
            }
            if(!data.field.quantity || data.field.quantity <= 0){
                layer.msg('请输入有效的数量');
                return false;
            }
            
            var stock = $('input[name="quantity"]').data('stock') || 0;
            var quantity = parseInt(data.field.quantity);
            
            if(quantity > stock){
                layer.msg('库存不足，当前库存: ' + stock);
                return false;
            }
            
            // 检查是否已经添加过该药品
            var tableData = table.getData('detailTable');
            var existingDrug = tableData.find(item => item.drugId === data.field.drugId);
            if(existingDrug){
                layer.confirm('该药品已在明细中，是否合并数量？', {
                    btn: ['合并','取消']
                }, function(){
                    // 检查合并后的数量是否超过库存
                    var totalQuantity = existingDrug.quantity + quantity;
                    if(totalQuantity > stock){
                        layer.msg('合并后数量超过库存限制');
                        return;
                    }
                    
                    existingDrug.quantity = totalQuantity;
                    existingDrug.amount = totalQuantity * existingDrug.price;
                    
                    detailTable.reload({
                        data: tableData
                    });
                    
                    // 重新计算总金额
                    var total = tableData.reduce(function(sum, item){
                        return sum + item.amount;
                    }, 0);
                    $('input[name="zongjia"]').val(total.toFixed(2));
                    
                    layer.msg('合并成功');
                });
                return false;
            }
            
            var detail = {
                drugId: data.field.drugId,
                drugName: $('select[name="drugId"] option:selected').text(),
                quantity: quantity,
                price: parseFloat(data.field.price),
                amount: parseFloat(data.field.price) * quantity
            };
            
            tableData.push(detail);
            detailTable.reload({
                data: tableData
            });
            
            // 计算总金额
            var total = tableData.reduce(function(sum, item){
                return sum + item.amount;
            }, 0);
            $('input[name="zongjia"]').val(total.toFixed(2));
            
            // 清空选择
            $('select[name="drugId"]').val('');
            $('input[name="quantity"]').val('');
            $('input[name="price"]').val('');
            form.render('select');
            
            return false;
        });
        
        // 表单提交
        form.on('submit(submitForm)', function(data){
            var tableData = table.getData('detailTable');
            if(tableData.length === 0){
                layer.msg('请添加销售明细');
                return false;
            }
            
            // 验证必填字段
            if(!data.field.responsiblePerson){
                layer.msg('请选择负责人');
                return false;
            }

            // 二次验证库存
            var stockPromises = tableData.map(function(detail) {
                return new Promise(function(resolve, reject) {
                    $.get('/api/drug/' + detail.drugId, function(res) {
                        if(res.code === 0) {
                            if(detail.quantity > (res.data.stock || 0)) {
                                reject('药品 ' + detail.drugName + ' 库存不足，当前库存: ' + (res.data.stock || 0));
                            } else {
                                resolve();
                            }
                        } else {
                            reject('获取药品库存失败');
                        }
                    });
                });
            });

            Promise.all(stockPromises).then(function() {
                // 所有库存验证通过，提交数据
                var formData = {
                    orderNo: data.field.danjuhao,
                    saleTime: new Date(data.field.shijian).toISOString(),  // 转换为ISO格式
                    totalPrice: parseFloat($('input[name="zongjia"]').val()),
                    operator: data.field.responsiblePerson,
                    remark: data.field.beizhu || '',
                    details: tableData
                };
                
                // 提交数据
                $.ajax({
                    url: '/sale/add',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(res) {
                        if(res.code === 0) {
                            layer.msg('添加成功', {
                                icon: 1,
                                time: 2000
                            }, function(){
                                // 跳转到列表页
                                window.location.href = 'xiaoshoumingxi.html';
                            });
                        } else {
                            layer.msg(res.msg || '添加失败');
                        }
                    }
                });
            }).catch(function(error) {
                layer.msg(error);
            });
            
            return false;
        });
        
        // 监听明细表格工具条
        table.on('tool(detailTable)', function(obj){
            if(obj.event === 'del'){
                // 获取当前表格数据
                var tableData = table.getData('detailTable');
                // 删除当前行
                tableData.splice(obj.tr.data('index'), 1);
                // 重新加载表格
                detailTable.reload({
                    data: tableData
                });
                // 重新计算总金额
                var total = tableData.reduce(function(sum, item){
                    return sum + item.amount;
                }, 0);
                $('input[name="zongjia"]').val(total.toFixed(2));
            }
        });
    });
</script>

<!-- 明细表格操作模板 -->
<script type="text/html" id="operationTpl">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</body>
</html>
